<!DOCTYPE HTML>
<html>
<head>
  <script type="application/javascript" src="pc.js"></script>
</head>
<body>
<pre id="test">
<script type="application/javascript">
"use strict";

createHTML({
  title: "MediaStream's 'addtrack' and 'removetrack' events with gUM",
  bug: "1208328"
});

runNetworkTest(function (options) {
  let test = new PeerConnectionTest(options);
  let eventsPromise;
  addRenegotiation(test.chain,
    [
      function PC_LOCAL_SWAP_VIDEO_TRACKS(test) {
        return getUserMedia({video: true}).then(stream => {
          const localStream = test.pcLocal._pc.getLocalStreams()[0];
          ok(localStream, "Should have local stream");

          const remoteStream = test.pcRemote._pc.getRemoteStreams()[0];
          ok(remoteStream, "Should have remote stream");

          const newTrack = stream.getTracks()[0];

          const videoSenderIndex =
            test.pcLocal._pc.getSenders().findIndex(s => s.track.kind == "video");
          isnot(videoSenderIndex, -1, "Should have video sender");

          test.pcLocal.removeSender(videoSenderIndex);
          test.pcLocal.attachLocalTrack(stream.getTracks()[0], localStream);

          const addTrackPromise = haveEvent(remoteStream, "addtrack",
              wait(50000, new Error("No addtrack event")))
            .then(trackEvent => {
              ok(trackEvent instanceof MediaStreamTrackEvent,
                 "Expected event to be instance of MediaStreamTrackEvent");
              is(trackEvent.type, "addtrack",
                 "Expected addtrack event type");
              is(trackEvent.track.id, newTrack.id, "Expected track in event");
              is(trackEvent.track.readyState, "live",
                 "added track should be live");
            })
            .then(() => haveNoEvent(remoteStream, "addtrack"));

          const remoteTrack = test.pcRemote._pc.getReceivers()
              .map(r => r.track)
              .find(t => t.kind == "video");
          ok(remoteTrack, "Should have received remote track");
          const endedPromise = haveEvent(remoteTrack, "ended",
              wait(50000, new Error("No ended event")));

          eventsPromise = Promise.all([addTrackPromise, endedPromise]);

          remoteStream.addEventListener("removetrack",
                                        function onRemovetrack(trackEvent) {
            ok(false, "UA shouldn't raise 'removetrack' when receiving peer connection");
          })
        });
      },
    ],
    [
      function PC_REMOTE_CHECK_EVENTS(test) {
        return eventsPromise;
      },
    ]
  );

  test.setMediaConstraints([{audio: true, video: true}], []);
  test.run();
});
</script>
</pre>
</body>
</html>
